package reflect;

import reflect.annotations.AutoRunClass;
import reflect.annotations.AutoRunMethod;

import java.io.File;
import java.lang.reflect.Method;
import java.net.URISyntaxException;

/**
 调用与当前类Test6在同一个包中被注解@AutoRunClass标注的类中
 那些被注解@AutoRunMethod标注的方法若干次(次数由该方法注解的参数确定)
 */
public class Test6 {
    public static void main(String[] args) throws Exception {
        File dir = new File(
                Test6.class.getResource(".").toURI()
        );
        String packagename = Test6.class.getPackage().getName();
        File[] subs = dir.listFiles(f -> f.getName().endsWith(".class"));
        for(File sub : subs) {
            String filename = sub.getName();
            String classname = filename.substring(0, filename.indexOf("."));
            Class cls = Class.forName(packagename + "." + classname);
            if(cls.isAnnotationPresent(AutoRunClass.class)) {
                Object obj = cls.newInstance();
                Method[] methods = cls.getDeclaredMethods();
                for(Method method : methods) {
                    if(method.isAnnotationPresent(AutoRunMethod.class)) {
                        AutoRunMethod arm = method.getAnnotation(AutoRunMethod.class);
                        int value = arm.value();
                        for (int i =0; i < value; i++) {
                            method.invoke(obj);
                        }

                    }
                }
            }

        }
    }
}
